package com.jzo2o.health.listener;

import com.jzo2o.api.trade.enums.TradingStateEnum;
import com.jzo2o.common.constants.MqConstants;
import com.jzo2o.common.model.msg.TradeStatusMsg;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.JsonUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.health.constant.TradeConstants;
import com.jzo2o.health.service.IOrdersCancelledService;
import com.jzo2o.health.service.IOrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 监听mq消息，接收支付结果
 *
 * @author itcast
 **/
@Slf4j
@Component
public class TradeStatusListener {

    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private IOrdersCancelledService ordersCancelledService;

    /**
     * 更新支付结果
     * 支付成功
     *
     * @param msg 消息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = TradeConstants.MQ_TRADE_QUEUE),
            exchange = @Exchange(name = MqConstants.Exchanges.TRADE, type = ExchangeTypes.TOPIC),
            key = MqConstants.RoutingKeys.TRADE_UPDATE_STATUS
    ))
    public void listenTradeUpdatePayStatusMsg(String msg) {
        log.info("接收到支付结果状态的消息 ({})-> {}", MqConstants.Queues.ORDERS_TRADE_UPDATE_STATUS, msg);

        //判断消息是否存在
        if (StringUtils.isBlank(msg)) {
            return;
        }

        //解析消息
        List<TradeStatusMsg> msgList = JsonUtils.toList(msg, TradeStatusMsg.class);
        if (CollUtils.isEmpty(msgList)){
            return;
        }

        //遍历集合
        for (TradeStatusMsg tradeStatus : msgList) {
            //如果支付来源是本服务，将支付成功，更新订单状态的方法
            if (ObjectUtils.equal(tradeStatus.getProductAppId(),TradeConstants.PRODUCT_APP_ID)
                && ObjectUtils.equal(tradeStatus.getStatusCode(), TradingStateEnum.YJS.getCode())){
                ordersService.paySuccess(tradeStatus.getTradingOrderNo(),tradeStatus.getTransactionId(),tradeStatus.getPaySuccessTime());
            }
        }

        log.info("订单状态变更：支付成功状态变更完毕");
    }

}
